#region license
# This file is part of Grawlix.
# 
# Grawlix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
# 
# Grawlix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with Grawlix.  If not, see
# <http://www.gnu.org/licenses/>.
#endregion

"""A wrapper for System.Drawing.Image that serializes properly."""

namespace Grawlix
import System
import System.Runtime.Serialization
import System.Security.Permissions

final class Image(ISerializable):
"""A wrapper for System.Drawing.Image that serializes properly."""
	
	def constructor([required] stream as IO.Stream):
	"""
	Construct an image from a given stream.
	Param stream: The stream to construct from.
	"""
		self(Drawing.Image.FromStream(stream))
	
	def constructor([required] image as Drawing.Image):
	"""
	Construct from the x and y coordinates.
	Param image: The image to construct.
	"""
		_image = image
	
	[SecurityPermission(
		SecurityAction.LinkDemand,
		Flags: SecurityPermissionFlag.SerializationFormatter)]
	protected def constructor(
		[required] info as SerializationInfo,
	    context as StreamingContext):
	"""
	Reconstructs the resource.
	Param info: The Serialization info available.
	Param context: The StreamingContext of the serialization.
	"""
		data = info.GetValue("ImageData", typeof((byte))) as (byte)
		if data is null:
			raise SerializationException(
				"Attempt to deserialize an image failed due to " +
				"missing image data.")
		using stream = IO.MemoryStream(data, false):
			_image = Drawing.Image.FromStream(stream)
	
	[SecurityPermission(
		SecurityAction.LinkDemand,
		Flags: SecurityPermissionFlag.SerializationFormatter)]
	def ISerializable.GetObjectData(
		[required] info as SerializationInfo,
	    context as StreamingContext):
	"""
	Get serialization info that can be used across AppDomains.
	Param info: The Serialization info available.
	Param context: The StreamingContext of the serialization.
	"""
		using stream = IO.MemoryStream():
			_image.Save(stream, _image.RawFormat)
			info.AddValue("ImageData", stream.ToArray(), typeof((byte)))
	
	[getter(ImageData)]
	private _image as Drawing.Image
	"""The wrapped image object."""
	
	
	